from django.http import JsonResponse
from rest_framework import serializers
from rest_framework.viewsets import ModelViewSet
from labor_price.models import People,Position
from rest_framework.response import Response
from django.contrib.auth.hashers import check_password ,make_password
from api.Position.view import PositionSerializer
import json
from rest_framework.decorators import action
from rest_framework.authentication import SessionAuthentication
from rest_framework import status
from django.views import View
from rest_framework.permissions import AllowAny,IsAdminUser,IsAuthenticated,IsAuthenticated,IsAuthenticatedOrReadOnly

class PeopleSerializer(serializers.ModelSerializer):
    Role = PositionSerializer(many=True)
    # Role = serializers.SlugRelatedField(queryset=Position.objects.all(),slug_field='jobName',many=True)
    # department_id = serializers.IntegerField()
    # department = serializers.SlugRelatedField(slug_field="name", read_only=True)

    # department = serializers.SlugRelatedField(slug_field='name', queryset=Department.objects.all())
    class Meta:
        model = People
        #fields = '__all__'
        exclude=['groups','user_permissions','is_superuser','is_staff']
        read_only_fields = ['last_login','date_joined']
        #给字段额外添加属性
        extra_kwargs = {
                        # 'password': {'write_only': True},
                        # 'first_name':{'required':True,'allow_blank':False,'trim_whitespace':True},
                        # 'last_name':{'required':True,'allow_blank':False,'trim_whitespace':True}
                        }

    def create(self, validated_data):
        user=super().create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user
    def update(self, instance, validated_data):
        instance = super().update(instance, validated_data)
        if validated_data.get('password'):
            instance.set_password(validated_data['password'])
            instance.save()
        return instance

#  添加和修改使用
class PeopleSerializer2(serializers.ModelSerializer):

    class Meta:
        model = People
        #fields = '__all__'
        exclude=['groups','user_permissions','is_superuser','is_staff']
        read_only_fields = ['last_login','date_joined']
        #给字段额外添加属性
        extra_kwargs = {
                        # 'password': {'write_only': True},
                        # 'first_name':{'required':True,'allow_blank':False,'trim_whitespace':True},
                        # 'last_name':{'required':True,'allow_blank':False,'trim_whitespace':True}
                        }

    def create(self, validated_data):
        user=super().create(validated_data)
        user.set_password(validated_data['password'])

        user.save()
        return user
    def update(self, instance, validated_data):
        instance = super().update(instance, validated_data)
        if validated_data.get('password'):
            instance.set_password(validated_data['password'])
            instance.save()
        return instance



class PeopleView(ModelViewSet):

    """
    list:
    返回人员列表数据

    read:
    返回人员详情数据

    create:
    添加人员信息

    update:
    编辑人员信息

    partial_update:
    patch  预获取

    destroy:
    删除人员信息
    """

    queryset = People.objects.all()  # 查询集
    serializer_class = PeopleSerializer  # 序列化器
    authentication_classes = [SessionAuthentication]
    permission_classes = [AllowAny]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        # for i in serializer.data:
        #     print(i['password'])
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        print(request)
        self.serializer_class = PeopleSerializer2
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def update(self, request, *args, **kwargs):
        self.serializer_class = PeopleSerializer2
        if (request.data['old_password']):
            a = check_password(request.data['old_password'], People.objects.get(id=request.data['id']).password)
            if a==False:
                return Response({'msg': '您输入的原密码不正确', 'status': 201})
        partial = kwargs.pop('partial', False)
        instance = self.get_object()

        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer.data)

    @action(methods=['put'], detail=False)
    def update_pwd(self, request):
        a = check_password(request.data['oldPwd'], People.objects.get(id=request.data['id']).password)
        if a == True:
            return Response({'msg': 'ok', 'status': 200})
        else:
            return Response({'msg': '您输入的原密码不正确', 'status': 201})

    def retrieve(self, request, *args, **kwargs):
        # self.serializer_class = PeopleSerializers
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

    @action(methods=['get'], detail=False)
    def batch_del(self, request):
        del_list = request.GET.get('del_list')
        del_list = json.loads(del_list)
        try:
            for i in (del_list):
                People.objects.get(id=i).delete()
        except:
            return Response({'msg': "批量删除失败", 'code': 400, 'data': '存在关联数据；不允许删除'})
        return Response({'msg': "批量删除成功", 'code': 200})

class People2(View):
    def post(self,req):
        data=json.loads(req.body)
        try:
            entryTime = data['entryTime']
        except:
            entryTime = ""
        try:
            name = data['name']
        except:
            name = ""
        try:
            phone = data['phone']
        except:
            phone = ""
        try:
            peopleState = data['peopleState']
        except:
            peopleState = ""
        try:
            Role = data['Role']
        except:
            Role = []

        aimdata = People.objects.create(name=name,phone=phone,entryTime=entryTime,peopleState=peopleState,username=data['username'],password=make_password(data['password']))
        for i in Role:
            print(i)
            aimdata.Role.add(i)
        aimdata.save()
        return JsonResponse({"message":"上传成功"})